package com.test.resumeanalysis.data.network

import com.test.resumeanalysis.util.LogUtil
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Interceptor
import okhttp3.Response

class BaseUrlInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val oldHttpUrl = request.url
        val builder = request.newBuilder()
        val headerValues = request.headers("urlName")
        if (headerValues != null && headerValues.isNotEmpty()) {
            builder.removeHeader("urlName")
            val headerValue = headerValues.get(0)
            var newBaseUrl: HttpUrl? = null;
            if (headerValue.equals("first")) {
                newBaseUrl = "http://139.9.208.251:8808".toHttpUrlOrNull()
            } else {
                newBaseUrl = oldHttpUrl
            }
            //重建新的HttpUrl,动态修改的Url部分
            val newFullUrl = oldHttpUrl
                .newBuilder()
                .scheme("http")
                .host(newBaseUrl!!.host)
                .port(newBaseUrl!!.port)
                .build()
            LogUtil.e("Url intercept  " + newFullUrl.toString())
            return chain.proceed(builder.url(newFullUrl).build())
        }
        return chain.proceed(request)
    }
}